<template>
  <vue-office-docx v-if="props.type == '.docx'" :src="props.srcUrl" @rendered="renderedHandler" @error="errorHandler" />
  <vue-office-pdf v-else-if="props.type == '.pdf'" :src="props.srcUrl" />
  <VueOfficeExcel
    v-else-if="props.type == '.xlsm' || props.type == '.xls' || props.type == '.xlsx'"
    ref="excelRef"
    style="height: 100vh; overflow: scroll"
    :src="props.srcUrl"
    @rendered="renderedHandler"
    @error="errorHandler"
  />
  <vue-office-docx v-else :src="docx" @rendered="renderedHandler" @error="errorHandler" />
</template>

<script setup name="viewOffice">
import { downloadFiles } from '@/api/loadProcessingAlgorithm/loadTaskManagement/index';
import { ref, defineProps } from 'vue';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
import '@vue-office/docx/lib/index.css';
import '@vue-office/excel/lib/index.css';
const excelRef = ref();
const props = defineProps({
  srcUrl: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: ''
  }
});
const docx = ref();
const renderedHandler = () => {
  // 修复插件bug：切换sheet 视图、滚动条高度未重置
  const ele = document.querySelector('.x-spreadsheet-menu');
  if (ele) {
    excelRef.value = ele;
    ele.addEventListener('click', resetScrollbar);
  }
};
// 重置的函数
function resetScrollbar() {
  // 横向滚动条
  const scrollbarElementX = document.querySelector('.x-spreadsheet-scrollbar.horizontal');
  // 竖向滚动条
  const scrollbarElementY = document.querySelector('.x-spreadsheet-scrollbar.vertical');

  // 竖向重置到顶部
  if (scrollbarElementY) {
    // 这一个延时器先保证excel视图的正确渲染
    setTimeout(() => {
      scrollbarElementY.scrollTop = 1;
    });
    // 这一个延时器再重置滚动条高度
    setTimeout(() => {
      scrollbarElementY.scrollTop = 0;
    }, 10);
  }

  // 横向重置到左侧
  if (scrollbarElementX) {
    // 这一个延时器先保证excel视图的正确渲染
    setTimeout(() => {
      scrollbarElementX.scrollLeft = 1;
    });
    // 这一个延时器再重置滚动条高度
    setTimeout(() => {
      scrollbarElementX.scrollLeft = 0;
    }, 10);
  }
}
const errorHandler = () => {};
const initData = async () => {
  if (!props.type) {
    const arr = [props.srcUrl];
    const res = await downloadFiles(arr);
    //读取文件的arrayBuffer
    res.arrayBuffer().then((res) => {
      docx.value = res;
    });
  }
};
onUnmounted(() => {
  initData();
  if (excelRef.value) {
    excelRef.value.removeEventListener('click', resetScrollbar);
  }
});
</script>
<style lang="scss" scoped></style>
